import AdmZip from "adm-zip"

import { koaBody } from "koa-body"

import { desktopPath } from "@/utils"

import { useKoa, useNode } from "@/hooks"

const { fs, os, path } = useNode()

const { createRouter } = useKoa()

const router = createRouter()

const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "uploadDir-"))

router.post(
  "/upload",
  koaBody({
    multipart: true,
    formidable: {
      multiples: false,
      keepExtensions: true,
      uploadDir,
      maxFileSize: 1024 * 1024 * 1024 * 10,
      onFileBegin(name, file) {
        fs.ensureDirSync(uploadDir)
        const { filepath, newFilename, originalFilename } = file
        file.filepath = filepath.replace(newFilename, originalFilename || "")
      },
    },
  }),

  async (ctx, next) => {
    const files = ctx.request.files
    const file = files && files[Object.keys(files)[0]]

    if (file && !Array.isArray(file)) {
      const { name: targetFolder } = path.parse(file.filepath)

      const zip = new AdmZip(file.filepath)

      const tmpDir = path.join(__dirname, "tmpDir")

      zip.extractAllTo(path.join(desktopPath, targetFolder), true)

      fs.rmSync(tmpDir, { recursive: true, force: true })
      fs.rmSync(uploadDir, { recursive: true, force: true })

      ctx.body = { status: 200, msg: "上传成功" }
    }

    next()
  },
)

export default router.routes()
